# V交流：18223205366
# 定时监测三要素可转债名单，大于130元，或名单变动则进行报警
# -*- coding:utf-8 -*-
"""
代码思路：
1、获取昨日名单以及今日名单
2、交易时间内每30分钟循环名单
3、检测昨日名单价格是否大于130元，如果大于，则报警
4、检测今日名单与昨日名单的差集，如果出现差集，则报警
"""
import json
import sys
from operator import itemgetter

from Config import global_config
from GetLoginData import get_jsl_data
from util.DateUtils import is_trade_time


class HandleData:

    def get_dat(self):
        dat = get_jsl_data()
        global full_data
        full_data = dat
        # print(dat)

        # 所有数据
        lst_data = []
        for row in dat['rows']:
            # 每一条数据
            lst_dat = []
            # 转债id
            id = row["id"]
            # 排名
            rank = 1
            dat_cell = row["cell"]
            # 是否赎回
            is_shui = dat_cell['force_redeem']
            if is_shui == None:
                # 转债名称
                name = dat_cell['bond_nm']
                # 现价
                price = dat_cell['price']
                # 溢价率
                yjl = dat_cell['premium_rt']
                # 评级
                rating_cd = dat_cell['rating_cd']
                # 剩余时间
                last_time = dat_cell['year_left']
                # 剩余规模
                last_scale = dat_cell['orig_iss_amt']
                # 到期税前收益
                ytm_rt = dat_cell['ytm_rt']
                # 双低
                # dblow = dat_cell['dblow']
                if ytm_rt == '-' or yjl == '-':
                    continue
                # 溢价率去掉%，取2位小数点
                yjl_num = round(float(yjl.strip("%")), 2)
                if yjl_num > 15:
                    continue
                # 到期税前收益去掉%，取2位小数点
                ytm_rt_num = round(float(ytm_rt.strip("%")), 2)
                if ytm_rt_num <= 0:
                    continue

                score = round(yjl_num + float(last_time) - ytm_rt_num, 2)

                lst_dat.append(rank)
                lst_dat.append(score)
                lst_dat.append(id)
                lst_dat.append(name)
                lst_dat.append(rating_cd)
                lst_dat.append(last_time)
                lst_dat.append(last_scale)
                # lst_dat.append(dblow)
                lst_dat.append(price)
                lst_dat.append(yjl)
                lst_dat.append(ytm_rt)
                lst_data.append(lst_dat)
            else:
                continue

        lst_data = sorted(lst_data, key=itemgetter(1), reverse=False)

        for index in range(len(lst_data)):
            lst_data[index][0] = index + 1

        return lst_data


def get_pre_data(path):
    import subprocess
    fh = subprocess.Popen("tail -n 2 {} |head -n 1".format(path), stdout=subprocess.PIPE, shell=True)
    for line in fh.stdout.readlines():
        return json.loads(line.decode('utf8').replace("'", "\""))


def get_last_price(data, zz_code):
    for row in data['rows']:
        # 转债id
        id = row["id"]
        if id == zz_code:
            price = row["cell"]['price']
            return price


def get_diff_data(pre_data, new_data):
    """
    检测今日名单与昨日名单的差集
    :param: pre_data
    :param: new_data
    :return:
    """
    pre_dict = {}
    new_dict = {}
    pre_arr = []
    new_arr = []
    message = "差集监测：\n"
    for arr in pre_data:
        pre_dict[arr[3]] = arr[7]
        pre_arr.append(arr[3])
    for arr in new_data:
        new_dict[arr[3]] = arr[7]
        new_arr.append(arr[3])
    sell_arr = [i for i in pre_arr if i not in new_arr]
    buy_arr = [i for i in new_arr if i not in pre_arr]
    # 应卖出转债
    message += "跌出新名单：\n"
    for arr in sell_arr:
        message += "{}，上期价格：{}\n".format(arr, pre_dict[arr])
    message += "----------------------------------\n"
    # 应买入转债
    message += "进入新名单：\n"
    for arr in buy_arr:
        message += "{}，当前价格：{}\n".format(arr, new_dict[arr])
    return message


is_notify = True


def get_beyond_price(pre_data):
    price = global_config.get('config', 'price')
    message = "价格监测：\n"
    n = 0
    for da in pre_data:
        last_price = get_last_price(full_data, da[2])
        if float(last_price) > float(price):
            message += "{}，现在价格：{}，已超过{}元\n".format(da[3], last_price, price)
            n += 1
    if n == 0:
        message += "暂无转债超过{}元\n".format(price)
        global is_notify
        is_notify = False
    return message


def timing_monitor_trade_time():
    """
    交易日定时监测
    :return:
    """
    if is_trade_time():
        message = ""
        # 获取最新名单
        new_data = HandleData().get_dat()[0:20]

        # 获取上期名单
        path = global_config.get('config', 'crontab_file_path')
        pre_data = get_pre_data(path)[0:20]
        # print("上期名单：")
        # for data in pre_data:
        #     print(data)

        # 名单差集监测
        message += get_diff_data(pre_data, new_data)
        message += "----------------------------------\n"
        # 价格监测
        message += get_beyond_price(pre_data)
        message += "----------------------------------\n"
        message += "最新名单："
        # print("最新名单：")
        for data in new_data:
            dat = [data[0], data[3], data[7]]
            message += dat.__str__() + "\n"
            # print(data)
        # print(message)
        return message
    else:
        print("当前不是交易时间")
        sys.exit()


def timing_monitor_all_time():
    """
    随时定时监测
    :return:
    """

    message = ""
    # 获取最新名单
    new_data = HandleData().get_dat()[0:20]

    # 获取上期名单
    path = global_config.get('config', 'crontab_file_path')
    pre_data = get_pre_data(path)[0:20]
    # print("上期名单：")
    # for data in pre_data:
    #     print(data)
    # message += "----------------------------------\n"

    # 名单差集监测
    message += get_diff_data(pre_data, new_data)
    message += "----------------------------------\n"
    # 价格监测
    message += get_beyond_price(pre_data)
    message += "----------------------------------\n"
    message += "最新名单：\n"
    # print("最新名单：")
    for data in new_data:
        # print(data)
        dat = [data[0], data[3], data[7]]
        message += dat.__str__() + "\n"
    # print(message)
    return message


if __name__ == '__main__':
    message = timing_monitor_all_time()
    print(message)
    if is_notify is True:
        print(message)
    else:
        sys.exit(1)
    # os.system("sh /Users/mlamp/code/kzz/kzz/shell/send_message.sh " + json.dumps(message))
    # timing_monitor_trade_time()
